<template>
  <div>
    <el-form v-if="isSearch" :inline="true" :model="traceForm">
      <el-form-item label="码">
        <el-input v-model="traceForm.code" placeholder="码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="custom-btn-primary" type="primary" @click="onTraceSubmit">追溯</el-button>
      </el-form-item>
    </el-form>
    <div v-if="traceInfo.code">
      <div class="trace-info-line">
        <span>追溯结果(码：{{traceInfo.code}})</span>
      </div>
      <div class="trace-info-line">
        <span>产品质量：<el-tag :type="traceInfo.status == 1 ? 'success' : 'danger'">{{traceInfo.status == 1 ? "OK" : "NG"}}</el-tag></span>
      </div>
      <div style="margin-top: 2vh">
        <el-timeline class="custom-timeline">
          <el-timeline-item v-for="(item,index) in traceInfo.moduleCycles" :key="'trace_' + index" :timestamp="item.beginTime" placement="top">
            <div>
              <h4>{{item.name}}</h4>
              <p v-if="item.endTime">完成于{{item.endTime}}</p>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>
  </div>
</template>

<script>

import {getRecordLifecycle} from "../request/Api";
import {Message} from "element-ui";

export default {
  name: 'ProductTrace',
  props: {
    isSearch: {
      type: Boolean,
      default: function () {
        return false;
      }
    },
    code: {
      type: String,
      default: function () {
        return "";
      }
    }
  },
  data () {
    return {
      traceForm: {
        code: null
      },
      traceInfo: {
        code: null,
        status: null,
        moduleCycles: []
      },
    }
  },
  created() {
    this.traceForm.code = this.code;
    if (this.traceForm.code) {
      this.onTraceSubmit();
    }
  },
  methods: {
    onTraceSubmit() {
      if (!this.traceForm.code) {
        Message.error("请输入要追溯的码");
        return false;
      }
      this.traceInfo.code = null;
      this.traceInfo.status = null;
      this.traceInfo.moduleCycles = [];
      getRecordLifecycle({codes: [this.traceForm.code]}).then(res => {
        if (res.code == 0) {
          if (res.data && res.data.lifeCycles && res.data.lifeCycles.length > 0) {
            this.traceInfo.code = res.data.lifeCycles[0].code;
            this.traceInfo.status = res.data.lifeCycles[0].status;
            this.traceInfo.moduleCycles = res.data.lifeCycles[0].moduleCycles;
          }
        } else {
          Message.error(res.msg);
        }
      })
    }
  },
  beforeDestroy() {

  }
}
</script>

<style scoped>

</style>
